<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/6/18
 * Time: 16:17
 */
namespace common\compents;

use common\models\Http;
use common\msg\UserMsg;
use yii\base\Behavior;
use yii\base\Controller;

class UserAuthBehavior extends Behavior{
    public $url = '/login.html';
    /**
     * @inheritdoc
     */
    public function attach($owner)
    {
        $this->owner = $owner;
        $owner->on(Controller::EVENT_BEFORE_ACTION, [$this, 'beforeFilter']);
    }

    /**
     * @inheritdoc
     */
    public function detach()
    {
        if ($this->owner) {
            $this->owner->off(Controller::EVENT_BEFORE_ACTION, [$this, 'beforeFilter']);
            $this->owner = null;
        }
    }

    public function beforeFilter(){
        $userInfo = Http::session('user');
        Http::session('referrer',\Yii::$app->request->getAbsoluteUrl());
        if(!$userInfo && strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') == false){
            $request = \Yii::$app->request;
            if($request->isAjax)
                exit(json_encode(array('status'=>0, 'msg'=>UserMsg::$login_lose)));
            else{
                $url = $this->url;
                header("location:$url");exit;
            }
        }

    }
}